package com.sdy.resdir.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.approval.api.ApprovalAllApi;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import com.sdy.resdir.biz.mapper.RdParameterInformationMapper;
import com.sdy.resdir.biz.mapper.RdResourceDirMapper;
import com.sdy.resdir.biz.model.*;
import com.sdy.resdir.biz.param.AddResParam;
import com.sdy.resdir.biz.service.*;
import com.sdy.resdir.biz.util.CopyUtil;
import com.sdy.resdir.biz.vo.ResInfoVo;
import com.sdy.usercenter.api.UserQueryApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 资源目录(总表) 服务实现类
 * </p>
 *
 * @author hyh
 * @since 2019-10-21
 */
@Slf4j
@Service
public class RdResourceDirServiceImpl extends BaseServiceImpl<RdResourceDir> implements RdResourceDirService {
    @Resource
    private RdResourceDirMapper rdResourceDirMapper;
    @Autowired
    private RdResDetailsApiService rdResDetailsApiService;
    @Resource
    private RdParameterInformationMapper paramMapper;
    @Autowired
    private RdResDataItemService rdResDataItemService;
    @Autowired
    private UserQueryApi userQueryApi;
    @Autowired
    private ApprovalAllApi approvalAllApi;
    @Autowired
    private RdResCreateInfoService rdResCreateInfoService;
    @Autowired
    private RdResourceApplicationDetailService rdResourceApplicationDetailService;
    @Autowired
    private RdImplementationOrderService rdImplementationOrderService;
    @Value("${res.dept.code}")
    private String deptCode;
    @Value("${res.app.code}")
    private String appCode;
    @Value("${res.approval.authCode}")
    private String authCode;
    @Value("${res.approval.roleCode}")
    private String roleCode;

    @Override
    public ResInfoVo getResInfoVo(Integer id, String implementationWorkOrder) throws BizException {
        RdResourceDir rdResourceDir = rdResourceDirMapper.selectById(id);
        Assert.isNull(rdResourceDir, "找不到该数据");
        ResInfoVo resInfoVo = CopyUtil.clone(rdResourceDir, ResInfoVo.class);
        resInfoVo.setDir(rdResourceDir);
        if (2 == rdResourceDir.getResType() || 1 == rdResourceDir.getResType()) {
            RdResDetailsApi api = rdResDetailsApiService.getOne(Wrappers.<RdResDetailsApi>lambdaQuery().eq(RdResDetailsApi::getResDirId, rdResourceDir.getId()));
            if (null != api) {
                List<RdParameterInformation> params = paramMapper.selectList(Wrappers.<RdParameterInformation>lambdaQuery().eq(RdParameterInformation::getOwnResId, api.getId()));
                api.setRequestParamInfo(params.stream().filter(param -> null != param && param.getParameterType() == 0).collect(Collectors.toList()));
                api.setReturnParamInfo(params.stream().filter(param -> null != param && param.getParameterType() == 1).collect(Collectors.toList()));
            }
            resInfoVo.setDetailsApi(api);
        } else {
            List<RdResDataItem> itemList = new ArrayList<>();
            if (implementationWorkOrder != null) {
                RdImplementationOrder order = rdImplementationOrderService.getOne(new LambdaQueryWrapper<RdImplementationOrder>().eq(RdImplementationOrder::getImplementationWorkOrder, implementationWorkOrder));
                if (order != null && order.getResType() != null && order.getResType() == 3) {
                    Assert.isTrue(StringUtil.isBlank(order.getApplyNum()), "无法获取资源详情");
                    RdResourceApplicationDetail one = rdResourceApplicationDetailService.getOne(new LambdaQueryWrapper<RdResourceApplicationDetail>().eq(RdResourceApplicationDetail::getApplyNumChild, order.getApplyNum()));
                    if (one != null) {
                        String itemId = one.getItemId();
                        if (StringUtil.isNotBlank(itemId)) {
                            List<Integer> itemIdList = new ArrayList(Arrays.asList(itemId.split(",")));
                            itemList = rdResDataItemService.list(new LambdaQueryWrapper<RdResDataItem>().in(RdResDataItem::getId, itemIdList));

                        }
                    }
                }
            }
            RdResourceDirData data = new RdResourceDirData();
            data.setDataItems(itemList);
            resInfoVo.setDirData(data);
        }
        return resInfoVo;
    }

    @Override
    public IPage<RdResourceDir> resPageList(Page page, Integer state, Integer type, String resName) {
        IPage<RdResourceDir> data = page(page, Wrappers.<RdResourceDir>lambdaQuery().eq(null != state, RdResourceDir::getIsRelease, state)
                .eq(null != type, RdResourceDir::getResType, type)
                .like(StringUtil.isNotEmpty(resName) && StringUtil.isNotBlank(resName), RdResourceDir::getResName, resName)
                .orderByDesc(RdResourceDir::getCreateTime));
        return data;
    }

    @Override
    public IPage<RdResourceDir> deptResPageList(Page page, Integer state, Integer type, String resName, Integer deptId) {
        IPage<RdResCreateInfo> pageData = rdResCreateInfoService.page(page, Wrappers.<RdResCreateInfo>lambdaQuery()
                .eq(RdResCreateInfo::getCreateDeptId, deptId).orderByDesc(RdResCreateInfo::getCreateTime));
        List<RdResCreateInfo> records = pageData.getRecords();
        Page<RdResourceDir> rdResourceDirPage = new Page<>();
        if (records.isEmpty()) {
            return rdResourceDirPage;
        }
        List<RdResourceDir> rdResourceDirs = rdResourceDirMapper.selectList(Wrappers.<RdResourceDir>lambdaQuery()
                .in(RdResourceDir::getId, records.stream().map(RdResCreateInfo::getResId).collect(Collectors.toList()))
                .eq(null != type, RdResourceDir::getResType, type)
                .eq(null != state, RdResourceDir::getResState, state)
                .like(StringUtil.isNotEmpty(resName) && StringUtil.isNotBlank(resName), RdResourceDir::getResName, resName)
                .orderByDesc(RdResourceDir::getId));
        rdResourceDirPage.setCurrent(page.getCurrent()).setSize(page.getSize()).setRecords(rdResourceDirs).setTotal(pageData.getTotal());
        return rdResourceDirPage;
    }

    @Override
    public int addRes(AddResParam resParam) throws Exception {
        RdResourceDir dir = CopyUtil.clone(resParam, RdResourceDir.class);
        Date now = new Date();
        dir.setModifyTime(now).setCreateTime(now).setResCode(UUID.randomUUID().toString()).setResState(1);
        if (dir.getIsRelease() == 1) {
            dir.setReleaseTime(now);
        }
        int insert = rdResourceDirMapper.insert(dir);
        boolean save = rdResCreateInfoService.save(new RdResCreateInfo().setResId(dir.getId())
                .setCreateTime(now).setCreateUserId(resParam.getUserId()).setCreateDeptId(resParam.getDeptId()));
        Assert.isTrue(insert == 0 || !save, "新增失败");
        if (dir.getIsRelease() == 1) {
            List<Integer> deptIdList = new ArrayList<>();
            List<Integer> roleIdList = new ArrayList<>();
            String insertApproval = null;
            int roleId = userQueryApi.getRoleByCode(roleCode).getId();
            // 已归集+受限
            if (dir.getCollectionSituation() == 1 && dir.getResPower() == 2) {
                Assert.isTrue(dir.getResPowerDeptId() == null, "资源受限必须选择权限审批部门");
                roleIdList.add(roleId);
                deptIdList.add(dir.getResPowerDeptId());
                roleIdList.add(roleId);
                deptIdList.add(userQueryApi.getDeptByCode(deptCode).getId());
                insertApproval = approvalAllApi.insertApproval(deptIdList, roleIdList, "[资源目录]-已归集", dir.getId().toString());
                // 未归集+受限
            } else if (dir.getCollectionSituation() == 2 && dir.getResPower() == 2) {
                Assert.isTrue(dir.getResPowerDeptId() == null, "资源受限必须选择权限审批部门");
                roleIdList.add(roleId);
                deptIdList.add(userQueryApi.getDeptByCode(deptCode).getId());
                roleIdList.add(roleId);
                deptIdList.add(dir.getResPowerDeptId());
                insertApproval = approvalAllApi.insertApproval(deptIdList, roleIdList, "[资源目录]-未归集", dir.getId().toString());
                // 已归集+公开
            } else if (dir.getCollectionSituation() == 1 && dir.getResPower() == 1) {
                roleIdList.add(roleId);
                deptIdList.add(userQueryApi.getDeptByCode(deptCode).getId());
                insertApproval = approvalAllApi.insertApproval(deptIdList, roleIdList, "[资源目录]-已归集", dir.getId().toString());
                // 未归集+公开
            } else if (dir.getCollectionSituation() == 2 && dir.getResPower() == 1) {
                roleIdList.add(roleId);
                deptIdList.add(userQueryApi.getDeptByCode(deptCode).getId());
                insertApproval = approvalAllApi.insertApproval(deptIdList, roleIdList, "[资源目录]-未归集", dir.getId().toString());
            }
            Assert.isTrue(insertApproval.equals("存在申请中的订单,不可重新发布"), "存在申请中的订单,不可重新发布");
            Assert.isTrue(insertApproval.equals("移除配置失败"), "移除配置失败");
            Assert.isTrue(insertApproval.equals("缺失部门的对应角色"), "缺失部门的对应角色");
            Assert.isTrue(insertApproval.equals("缺失角色的对应部门"), "缺失角色的对应部门");
            Assert.notTrue(insertApproval.equals("流程生成成功"), "流程生成失败");

            if (dir.getCollectionSituation().equals(1)) {

            } else {
                approvalAllApi.insertApproval(deptIdList, roleIdList, "[资源目录]-未归集", dir.getId().toString());
            }
        }
        return 1;
    }

}
